﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace RENIT.DragNDropUpload.Utils
{
    public class ObjectReader<T>
    {
        private object data;
        private static Type type = typeof(T);
        private static Dictionary<string, FieldInfo> fields = new Dictionary<string,FieldInfo>(); 
        
        public ObjectReader(T obj)
        {
            data = obj;
            IntializeFields();

        }

        private void IntializeFields()
        {
            if (fields.Count == 0)
            {
                foreach (var f in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
                {
                    fields.Add(f.Name, f);
                }
            }
        }

        public string GetStringField(string fldName)
        {
            var value = GetFieldValue(fldName);
            return value == null ? null : value.ToString();
        }

        private object GetFieldValue(string fldName)
        {
            return fields[fldName].GetValue(data);
        }

    }

    public static class ObjectReaderFactory
    {
        public static ObjectReader<T> GetObjectReader<T>(this T instance)
        {
            return new ObjectReader<T>(instance);
        }
    }


}
